package com.etc.dao.impl;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.sql.rowset.CachedRowSet;

import com.etc.dao.MomentsDao;
import com.etc.entity.Moments;
import com.etc.entity.User;
import com.etc.util.DBUtil;
import com.etc.util.PageData;

/**
 * 
 * @author zww
 *
 */
public class MomentsDaoImpl implements MomentsDao{

	/**
	 * 添加时刻表
	 */
	@Override
	public boolean insertments(Moments moments) {
		if(null!=moments) {
			String sql="insert into moments values(null,?,?,?)";
			return DBUtil.executeUpdate(sql, moments.getM_begin(),moments.getM_end(),moments.getM_interval());			
		}
		return false;
	}

	/**
	 * 查询车辆的时刻信息
	 */
	@Override
	public List<Moments> queryMents() {
		String sql="select * from moments";
		CachedRowSet crs = DBUtil.execQuery(sql);
		Moments moments=null;
		List<Moments> list=new ArrayList<Moments>();
		try {
			while(crs.next()) {
				int m_id = crs.getInt(1);
				String m_begin = crs.getString(2);
				String m_end = crs.getString(3);
				String m_interval = crs.getString(4);
				moments = new Moments(m_id, m_begin, m_end, m_interval);
				list.add(moments);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return list;
	}



	@Override
	public PageData queryMomentsByLikeAndLimit(int pageNo, int pageSize, String mlike) {
		List<Moments> list =new ArrayList<Moments>();
		String sql = "select * from moments where m_interval like ? limit ?,?";
		CachedRowSet crs = DBUtil.execQuery(sql,"%"+mlike+"%",(pageNo-1)*pageSize,pageSize);
		try {
			while(crs.next()) {
				int m_id = crs.getInt(1);
				String m_begin = crs.getString(2);
				String m_end = crs.getString(3);
				String m_interval = crs.getString(4);
				list.add(new Moments(m_id, m_begin, m_end, m_interval));
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		int totalCount=0;
		String sql2="select count(*) from moments where m_interval like ?";
		CachedRowSet crs2 = DBUtil.execQuery(sql2,"%"+mlike+"%");
		try {
			while(crs2.next()) {
				totalCount=crs2.getInt(1);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		PageData pageData = new PageData(list, pageNo, pageSize, totalCount);
		return pageData;
	}

	/**
	 * 修改时刻信息
	 */
	@Override
	public boolean updateMonents(Moments moments) {
		if(null!=moments) {
			String sql="update moments set m_begin=?,m_end=?,m_interval=? where m_id=?";
			return DBUtil.executeUpdate(sql, moments.getM_begin(),moments.getM_end(),moments.getM_interval(),moments.getM_id());
		}
		return false;
	}

	/**
	 * 删除时刻信息
	 */
	@Override
	public boolean delMoments(int mid) {
		if(mid!=0) {
			String sql="delete from moments where m_id=?";
			return DBUtil.executeUpdate(sql, mid);
		}
		return false;
	}

}
